<template>
	<div class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form ref="form" :inline="true" :model="queryData">
					<el-form-item label="邀请人账号:" prop="inviteUserName">
						<el-input
							v-model="queryData.inviteUserName"
							placeholder="请输入"
							:maxlength="11"
							clearable
							style="width: 180px"
						></el-input>
					</el-form-item>
					<el-form-item label="被邀请人账号:" prop="inviteesUserName">
						<el-input
							v-model="queryData.inviteesUserName"
							placeholder="请输入"
							:maxlength="11"
							clearable
							style="width: 180px"
						></el-input>
					</el-form-item>
					<el-form-item label="" class="time-options">
						<el-select
							v-model="queryData.timeOptionType"
							placeholder="请选择"
							style="width:150px;margin-right: -5px;"
						>
							<el-option label="首存时间:" :value="1"></el-option>
							<el-option label="注册时间:" :value="2"></el-option>
						</el-select>
						<el-date-picker
							v-model="searchTime"
							:picker-options="pickerOptions1"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							align="right"
							:clearable="true"
							:default-time="defaultTime"
							style="width: 375px"
							class="time-options-value"
						></el-date-picker>
					</el-form-item>
					<el-form-item label="是否达标:">
						<el-select
							v-model="queryData.status"
							clearable
							placeholder="默认选择全部"
							:popper-append-to-body="false"
						>
							<el-option
								:label="'全部'"
								:value="undefined"
							></el-option>
							<el-option label="是" :value="1"></el-option>
							<el-option label="否" :value="0"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="是否过有效期:">
						<el-select
							v-model="queryData.validityPeriodStatus"
							clearable
							placeholder="默认选择全部"
							:popper-append-to-body="false"
						>
							<el-option
								:label="'全部'"
								:value="undefined"
							></el-option>
							<el-option label="是" :value="1"></el-option>
							<el-option label="否" :value="0"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item class="">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="flag"
							@click="search"
						>
							{{ queryText }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="resetFlag"
							@click="reset"
						>
							重置
						</el-button>
						<el-button
							v-if="hasPermission('347')"
							icon="el-icon-download"
							type="warning"
							:disabled="loading"
							@click="exportExcel"
						>
							导出
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div class="content">
				<CommonTable
					ref="hasTotalTable"
					:loading="loading"
					:datas="tableOptions.datas"
					:fieldList="tableOptions.fieldList"
					:operation="tableOptions.operation"
					:pageObj="pageObj"
					:summary="tableOptions.summary"
					:getSummariesObj="tableOptions.getSummariesObj"
					:loadData="loadData"
					@showDetail="showDetail"
				></CommonTable>
				<!-- 分页 -->
				<!-- <el-pagination
					:current-page.sync="pageNum"
					background
					class="fenye"
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="[10, 20, 50]"
					:total="total"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination> -->
			</div>
		</div>
		<el-dialog
			v-if="visibleDetail"
			:close-on-click-modal="false"
			:destroy-on-close="true"
			:visible.sync="visibleDetail"
			width="70%"
			title="返利明细"
			@close="visibleDetail = false"
		>
			<CommonTable
				:xvhao="true"
				:datas="tableOptions1.datas"
				:pageObj="{ show: false }"
				:fieldList="tableOptions1.fieldList"
			></CommonTable>
		</el-dialog>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import CommonTable from '@/components/CommonTable'
export default {
	name: routerNames.clientProfitAndLoss,
	components: {
		CommonTable
	},
	mixins: [list],
	data() {
		return {
			visibleDetail: false,
			current: {},
			tableOptions: {
				datas: [],
				fieldList: [
					{
						label: '邀请人账号',
						prop: 'inviteUserName',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '被邀请人账号',
						prop: 'inviteesUserName',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '注册时间',
						prop: 'registerAt',
						filter: (val) => val || '-',
						orderColumn: true,
						show: true
					},
					{
						label: '首存时间',
						prop: 'firstDepositTime',
						orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '开始返利时间',
						prop: 'startRebateTime',
						orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '结束返利时间',
						prop: 'endRebateTime',
						orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					// 字段错误
					{
						label: '累计有效流水',
						prop: 'validBetAmount',
						orderColumn: true,
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '累计返利',
						prop: 'rebateAmount',
						orderColumn: true,
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '是否达标',
						prop: 'status',
						// orderColumn: true,
						filter: (val) => {
							if (val || val === 0) {
								return {
									0: '否',
									1: '是'
								}[val]
							} else {
								return '-'
							}
						},
						show: true
					},
					{
						label: '总派发返利',
						prop: 'totalRebate',
						orderColumn: true,
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '剩余返利金额',
						prop: 'remainRebateAmount',
						orderColumn: true,
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '返利有效期',
						prop: 'rebateValidity',
						// orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '是否过有效期',
						prop: 'validityPeriodStatus',
						// orderColumn: true,
						filter: (val) => {
							if (val || val === 0) {
								return {
									0: '否',
									1: '是'
								}[val]
							} else {
								return '-'
							}
						},
						show: true
					},
					{
						label: '操作',
						show: true,
						width: '80',
						buttonLists: [
							{
								label: '查看',
								btnType: 'primary',
								filtersShow: (val) => {
									return true
								},
								event: 'showDetail',
								eventArg: null,
								disabled: (val) => {
									return false
								}
							}
						]
					}
				],
				summary: {
					show: true,
					showTotal: false,
					datas: {},
					// 小计
					columns: [
						{
							validBetAmount: '累计有效流水',
							key: 'validBetAmount',
							filter: (val) => this.formatMoney(val)
						},
						{
							rebateAmount: '累计返利',
							key: 'rebateAmount',
							filter: (val) => this.formatMoney(val)
						},
						{
							totalRebate: '总派发返利',
							key: 'totalRebate',
							filter: (val) => this.formatMoney(val)
						},
						{
							remainRebateAmount: '剩余返利金额',
							key: 'remainRebateAmount',
							filter: (val) => this.formatMoney(val)
						}
					],
					// 总计
					totalColumns: [
						{
							validBetAmount: '累计有效流水',
							key: 'validBetAmountTotal',
							filter: (val) => this.formatMoney(val)
						},
						{
							rebateAmount: '累计返利',
							key: 'rebateAmountTotal',
							filter: (val) => this.formatMoney(val)
						},
						{
							totalRebate: '总派发返利',
							key: 'totalRebateTotal',
							filter: (val) => this.formatMoney(val)
						},
						{
							remainRebateAmount: '剩余返利金额',
							key: 'remainRebateAmountTotal',
							filter: (val) => this.formatMoney(val)
						}
					]
				}
			},
			tableOptions1: {
				datas: [],
				fieldList: [
					{
						label: '返利时间',
						prop: 'rebateTime',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: '有效流水',
						prop: 'validBetAmount',
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '返利比例',
						prop: 'betRewardRate',
						filter: (val) => val + '%' || '-',
						show: true
					},
					{
						label: '最低返利金额',
						prop: 'betRewardMin',
						show: true,
						filter: (val) => this.formatMoney(val)
					},
					{
						label: '单个好友最高返利金额',
						prop: 'betRewardMax',
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '返利金额',
						prop: 'rebateAmount',
						filter: (val) => this.formatMoney(val),
						show: true
					},
					{
						label: '返利状态',
						prop: 'rebateType',
						filter: (val) =>
							this.typeFilter(val, 'activityInviteDetailsType'),
						show: true
					},
					{
						label: '剩余返利金额',
						prop: 'remainRebateAmount',
						filter: (val) => this.formatMoney(val),
						show: true
					}
				]
			},
			queryData: {
				timeOptionType: 1
			},
			searchTime: [],
			day31: 31 * 24 * 3600 * 1000,
			flag: false,
			resetFlag: false,
			queryText: '查询',
			tableData: [],
			dialogList: [],
			pageR: 1,
			sizeR: 10,
			dialogTotal: 0,
			deviceTypeCode: '',
			summary: null,
			title: '',
			visible: false,
			loadingDialog: false,
			pageObj: {
				show: true,
				pageTotal: 0
			}
		}
	},
	methods: {
		showDetail(obj) {
			this.loading = true
			this.$api
				.getActivityInviteBetDetailsPayloadApi({
					inviteBetId: obj.inviteBetId || obj.id
				})
				.then((res) => {
					this.loading = false
					if (res.code === 200) {
						this.tableOptions1.datas = res.data || []
						this.visibleDetail = true
					}
				})
				.catch((err) => {
					this.loading = false
					throw err
				})
		},
		vipSerialNumFn(val) {
			if (val === '') return
			if (
				(+val < +this.queryData.vipSerialNumMin &&
					this.queryData.vipSerialNumMin) ||
				(+val > +this.queryData.vipSerialNumMax &&
					this.queryData.vipSerialNumMax)
			) {
				// eslint-disable-next-line no-extra-semi
				;[
					this.queryData.vipSerialNumMin,
					this.queryData.vipSerialNumMax
				] = [
					this.queryData.vipSerialNumMax,
					this.queryData.vipSerialNumMin
				]
			}
		},
		loadData(orderParams) {
			if (this.queryData.validityPeriodStatus === '') {
				delete this.queryData.validityPeriodStatus
			}
			if (this.queryData.status === '') {
				delete this.queryData.status
			}
			if (orderParams) {
				const { orderType, orderKey } = orderParams
				// 排序列:0=注册时间 1=首存时间,2=开始返利时间,3=结束返利时间,4=累计有效流水,5=累计返利,6=总派发返利,7=剩余返利金额
				const obj = {
					registerAt: 0,
					firstDepositTime: 1,
					startRebateTime: 2,
					endRebateTime: 3,
					validBetAmount: 4,
					rebateAmount: 5,
					totalRebate: 6,
					remainRebateAmount: 7,
					status: 8,
					rebateValidity: 9
				}
				this.queryData.orderKey = obj[orderKey]
				this.queryData.orderType = orderType
			}
			const create = this.searchTime || []
			const [startTime, endTime] = create
			const params = {
				...this.$refs.hasTotalTable.getParams(this.queryData),
				type: this.queryData.timeOptionType,
				beginTime: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss') // HH:mm:ss
					: '',
				endTime: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: ''
			}

			delete params.timeOptionType
			if (this.searchTime?.length === 0) {
				delete params.type
			}
			// if (endTime - startTime >= this.day31) {
			// 	this.$message.warning('请缩小搜索范围至31天')
			// } else {
			this.loading = true
			Promise.all([this.$api.getActivityInviteBetPayloadApi(params)])
				.then(([res, res2]) => {
					if (res.code === 200) {
						this.tableOptions.datas = []
						this.tableData = res?.data?.record || []
						this.pageObj.pageTotal = res?.data?.totalRecord || 0
						this.tableOptions.datas = this.tableData || []
						this.tableOptions.summary.datas = res.data.summary || []
						this.tableOptions.summary.show = true
						this.tableOptions.summary.showTotal = true
					}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
			// }
		},
		search() {
			this.$refs.hasTotalTable.pageNum = 1
			this.loadData()
		},
		reset() {
			// const S = dayjs()
			// 	.startOf('day')
			// 	.valueOf()
			// const E = dayjs()
			// 	.endOf('day')
			// 	.valueOf()
			this.queryData = {}
			this.searchTime = []
			this.$refs.hasTotalTable.pageNum = 1
			this.search()
		},
		exportExcel() {
			this.loading = true
			const create = this.searchTime || []
			const [startTime, endTime] = create
			const params = {
				...this.$refs.hasTotalTable.getParams(this.queryData),
				type: this.queryData.timeOptionType,
				beginTime: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: '',
				endTime: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: ''
			}
			delete params.timeOptionType
			if (this.searchTime?.length === 0) {
				delete params.type
			}
			this.$confirm(
				`<strong>是否导出?</strong></br><span style='font-size:12px;color:#c1c1c1'>数据过大时，请耐心等待</span>`,
				'确认提示',
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
				.then(() => {
					this.$api
						.getActivityInviteBetDownloadApi(params)
						.then((res) => {
							this.loading = false
							const { data, status } = res
							if (res && status === 200) {
								const { type } = data
								if (type.includes('application/json')) {
									const reader = new FileReader()
									reader.onload = (evt) => {
										if (evt.target.readyState === 2) {
											const {
												target: { result }
											} = evt
											const ret = JSON.parse(result)
											if (ret.code !== 200) {
												this.$message({
													type: 'error',
													message: ret.msg,
													duration: 1500
												})
											}
										}
									}
									reader.readAsText(data)
								} else {
									const result = res.data
									const disposition =
										res.headers['content-disposition']
									const fileNames =
										disposition && disposition.split("''")
									let fileName = fileNames[1]
									fileName = decodeURIComponent(fileName)
									const blob = new Blob([result], {
										type: 'application/octet-stream'
									})
									if (
										'download' in
										document.createElement('a')
									) {
										const downloadLink = document.createElement(
											'a'
										)
										downloadLink.download = fileName || ''
										downloadLink.style.display = 'none'
										downloadLink.href = URL.createObjectURL(
											blob
										)
										document.body.appendChild(downloadLink)
										downloadLink.click()
										URL.revokeObjectURL(downloadLink.href)
										document.body.removeChild(downloadLink)
									} else {
										window.navigator.msSaveBlob(
											blob,
											fileName
										)
									}
									this.$message({
										type: 'success',
										message: '导出成功',
										duration: 1500
									})
								}
							}
						})
						.catch(() => {
							this.loading = false
							// this.$message({
							// 	type: 'error',
							// 	message: '导出失败',
							// 	duration: 1500
							// })
						})
				})
				.catch(() => {
					this.loading = false
				})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	color: #5c5c5c;
	font-weight: 700;
	display: flex;
}
.count_row {
	height: 80px;
	color: #5c5c5c;
	p {
		height: 40px;
		line-height: 40px;
		font-weight: 700;

		span {
			display: inline-block;
			width: 20px;
			height: 20px;
		}
	}
}
.fenye {
	text-align: center;
}
::v-deep .el-input__inner {
	padding: 1px 10px;
}
.setting-div {
	display: inline-block;
	min-width: 90px;
}
</style>
